Completed
Pull Request — develop (#75)
by
unknown
01:29
created

math.js ➔ ... ➔ distanceLink   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 4
c 2
b 0
f 0
nc 4
dl 0
loc 17
rs 9.2
nop 3
1
define(function () {
2
  return {
3
    distance: function distance(a, b) {
4
      return Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2);
5
    },
6
7
    distancePoint: function distancePoint(a, b) {
8
      return Math.sqrt(distance(a, b));
9
    },
10
11
    distanceLink: function distanceLink(p, a, b) {
12
      /* http://stackoverflow.com/questions/849211 */
13
      var l2 = distance(a, b);
14
      if (l2 === 0) {
15
        return distance(p, a);
16
      }
17
      var t = ((p.x - a.x) * (b.x - a.x) + (p.y - a.y) * (b.y - a.y)) / l2;
18
      if (t < 0) {
19
        return distance(p, a);
20
      } else if (t > 1) {
21
        return distance(p, b);
22
      }
23
      return distancePoint(p, {
24
        x: a.x + t * (b.x - a.x),
25
        y: a.y + t * (b.y - a.y)
26
      });
27
    }
28
  };
29
});
30